/***************************************************************************
 *   This is a part of the NextCAD Web APP.                                *
 *   Copyright (C) AMCAX, All rights reserved.                             *
 ***************************************************************************/

import {
  pickedFaceData,
  pickedLineData,
  pickedModelData,
  pickedVertexData,
} from '@amcax/base';
import { previewer } from '@app-cad/module';
import { PickInputRJSFFormat } from '@app-cad/common/components/command-form/constants';
import { PickableCommandForm } from '@app-cad/common/components/command-form/pickable';
import { useCommand } from '@app-cad/common/hooks/useCommand';
import { useTools } from '@app-cad/common/hooks/useTools';
import { getIdOfPickedObj } from '@app-cad/common/utils/render';
import { CurvedBaseCommand, CurvedCmdDialogParams } from '@app-cad/types';
import { RJSFSchema } from '@rjsf/utils';
import { useAsyncEffect } from 'ahooks';
import i18n from 'i18next';
import { useEffect, useState } from 'react';
import { isEmpty } from 'lodash';

type pickedALLType =
  | pickedModelData
  | pickedFaceData
  | pickedLineData
  | pickedVertexData;

type FormData = {
  base?: pickedALLType | pickedALLType[];
};

type Params = {
  base: string;
};

function CommandPick({ title, onClose, props }: CurvedCmdDialogParams) {
  const { picker } = useTools();
  const [formData, setFormData] = useState<FormData>({});

  useEffect(() => {
    preview();
  }, [formData]);

  useAsyncEffect(async () => {
    if (props == null) {
      setFormData({});
      return;
    }

    const params: Params = props.params;
    const { base } = params;

    await initEditDependency([base]);

    setFormData({
      base: picker.generatePickObjByPickID(base),
    });
  }, [props?.shape]);

  const preview = async () => {
    props ? previewer.clear() : clear();
    if (!isFormDataValid()) return;

    await execute(true);
  };

  const checkAndFinishDraw = async () => {
    if (!isFormDataValid()) {
      return;
    }

    await execute(false);

    onClose();
  };

  const execute = async (preview: boolean) => {
    const params = {
      a: {
        base:
          formData.base instanceof Array
            ? formData.base.map((item) => getIdOfPickedObj(item))
            : getIdOfPickedObj(formData.base),
      },
    };

    await confirmCommand(params, preview);
  };

  const isFormDataValid = () => {
    return !isEmpty(formData.base);
  };

  const { initEditDependency, initingEdit, clear, confirmCommand, isLoading } =
    useCommand('cmd-pick', {
      commandName: 'CreatePicker',
      editDxid: props?.shape,
      onClose,
      finishDraw: checkAndFinishDraw,
    });

  const schema: RJSFSchema = {
    type: 'object',
    properties: {
      base: props?.shape
        ? {
            type: 'string',
            format: PickInputRJSFFormat.PickALL,
          }
        : {
            type: 'array',
            items: {
              type: 'string',
              enum: [],
            },
            format: PickInputRJSFFormat.MultiPickALL,
            uniqueItems: true,
          },
    },
  };

  return (
    <PickableCommandForm
      disabled={initingEdit}
      onClose={onClose}
      submitLoading={isLoading}
      title={title}
      schema={schema}
      formData={formData}
      onChange={(v) => {
        setFormData(v);
      }}
      extraUiSchema={{
        base: {
          'ui:placeholder': '提取对象',
          'ui:autofocus': true,
        },
      }}
      submitText='完成'
      onSubmit={checkAndFinishDraw}
      isFormDataValid={isFormDataValid()}
    />
  );
}

export const cmdPick: CurvedBaseCommand = {
  id: 'CommandPick',
  label: 'command.pick',
  icon: 'commands/curved/pick',
  create: (label, onClose, props) => (
    <CommandPick
      title={i18n.t(label)}
      onClose={onClose}
      props={props}
    />
  ),
};
